<template>
  <div id="user-list">
    <div class="title mb-10">
      <Divider style="margin-top: 10px;">
        <h3 style="color: #17233d;">
          {{ title }}
        </h3>
      </Divider>
    </div>
    <div class="top-toolbar pr-10 pl-10">
      <Row type="flex" v-if="userAccess.indexOf('ROLE_INSTITUTE_ADMIN') > -1 || userAccess.indexOf('ROLE_SCHOOL_ADMIN') > -1 || userAccess.indexOf('ROLE_ROOT') > -1">
        <Col :xs="24" :sm="24" :md="12" :lg="7" class="mb-15">
          <span>学院：</span>
          <div style="display: inline-block;width: calc(100% - 42px);">
            <Select
              v-if="userAccess.indexOf('ROLE_SCHOOL_ADMIN') > -1 || userAccess.indexOf('ROLE_ROOT') > -1"
              :size="selectSize" v-model="filter.departments"
              :enabledPreventOverflow="enabledPreventOverflow"
              placeholder="请选择学院进行检索" filterable>
              <Option v-for="(item, index) in options.institutes" :value="item" :key="index">{{ item }}</Option>
            </Select>
            <Input v-else v-model="filter.departments[0]" readonly placeholder="当前学院" />
          </div>
        </Col>
        <Col :xs="24" :sm="24" :md="{span: 11, offset: 1}" :lg="{span: 7, offset: 1}" class="mb-15">
          <span>身份：</span>
          <div style="display: inline-block;width: calc(100% - 42px);">
            <Select :size="selectSize"
                    v-model="filter.identity"
                    :enabledPreventOverflow="enabledPreventOverflow"
                    placeholder="请选择身份进行检索"
                    filterable>
              <Option value="all" key="all">全部</Option>
              <Option value="Teacher" key="Teacher">教师</Option>
              <Option value="Student" key="Student">学生</Option>
              <Option value="Other" key="Other">临时</Option>
              <Option value="Phone" key="Phone">访客</Option>
              <Option value="Adult" key="Adult">继续教育学院学生</Option>
              <Option value="Staff" key="Staff">职工</Option>
            </Select>
          </div>
        </Col>
        <Col :xs="24" :sm="24" :md="12" :lg="{span: 8, offset: 1}" class="mb-15">
          <span>权限：</span>
          <Select style="width: calc(100% - 42px);"
                  :size="selectSize"
                  v-model="filter.roles"
                  :enabledPreventOverflow="enabledPreventOverflow"
                  placeholder="请选择权限进行检索"
                  filterable>
            <Option value="all" key="all">全部</Option>
            <Option v-for="(item, index) in roleOptions" :value="item.value" :key="index">{{ item.label }}</Option>
          </Select>
        </Col>
      </Row>
      <Row type="flex">
      </Row>
      <Row type="flex">
        <Col :xs="{span: 24, order: 3}" :sm="{span: 24, order: 3}" :md="{span: 24, order: 3}" :lg="{span: 8, order: 1}">
          <Button type="info" @click="addUser" class="mb-15">
            <font-awesome-icon icon="plus-circle"/>
            添加用户
          </Button>
          <Divider type="vertical" class="mb-15"/>
          <Button type="success" @click="batchEnable" class="mb-15" :disabled="table.selection.length === 0">
            <font-awesome-icon icon="check-circle"/>
            批量启用
          </Button>
          <Divider type="vertical" class="mb-15"/>
          <Button type="error" @click="batchDisable" class="mb-15" :disabled="table.selection.length === 0">
            <font-awesome-icon icon="minus-circle"/>
            批量禁用
          </Button>
        </Col>
        <Col :xs="{span: 24, order: 1}" :sm="{span: 24, order: 1}" :md="{span: 12, order: 1}" :lg="{span: 7, order: 2}" class="mb-15">
          <span>状态：</span>
          <Select style="width: calc(100% - 42px);"
                  :size="selectSize"
                  v-model="filter.enabled"
                  :enabledPreventOverflow="enabledPreventOverflow"
                  placeholder="请选择状态进行检索"
                  filterable>
            <Option value="all" key="all">全部</Option>
            <Option :value="1" key="1">正常</Option>
            <Option :value="0" key="0">禁用</Option>
          </Select>
        </Col>
        <Col :xs="{span: 24, order: 2}" :sm="{span: 24, order: 2}" :md="{span: 11, offset: 1, order: 2}" :lg="{span: 8, offset: 1, order: 3}" class="mb-15">
            <Input v-model="search.keyword"
                   search
                   clearable
                   :disabled="!search.criteria"
                   :placeholder="inputPlaceholder"
                   @on-search="onSearch"
                   @on-change="onInputChange">
              <Select slot="prepend"
                      style="width: 90px;"
                      :size="selectSize"
                      v-model="search.criteria"
                      :enabledPreventOverflow="enabledPreventOverflow"
                      placeholder="搜索条件"
                      filterable
                      clearable
                      @on-change="onChangeSearchCriteria">
                <Option value="name" key="name">姓名</Option>
                <Option value="code" key="code">工号</Option>
                <Option value="tel" key="tel">手机号</Option>
                <Option value="email" key="email">邮箱</Option>
              </Select>
            </Input>
          </Col>
      </Row>
    </div>
    <div class="table-container small-table">
      <Table :border="table.showBorder"
             :stripe="table.showStripe"
             :show-header="table.showHeader"
             :height="table.fixedHeader ? table.height : ''"
             :size="table.size"
             :data="table.data"
             :columns="table.columns"
             :loading="table.loading"
             :disabledHover="table.disabledHover"
             :highlight-row="table.highlightRow"
             @on-sort-change="onSortChange"
             @on-selection-change="onSelectionChange">
        <template slot-scope="{ row, index }" slot="action">
          <div style="padding-top: 5px; padding-bottom: 5px;">
            <Button type="primary" :size="btnSize" @click="edit(row)" :disabled="isDisabled(row.roles)">
              <font-awesome-icon icon="edit"/>
              授权
            </Button>
            <Button v-if="row.enabled" type="dashed" :size="btnSize" class="mt-10" @click="disable(row)" :disabled="isDisabled(row.roles)">
              <font-awesome-icon icon="ban"/>
              禁用
            </Button>
            <Button v-else type="success" :size="btnSize" class="mt-10" @click="enable(row)" :disabled="isDisabled(row.roles)">
              <font-awesome-icon icon="dot-circle"/>
              启用
            </Button>
          </div>
        </template>
      </Table>
    </div>
    <div class="pagination text-right pr-15 mt-20">
      <Page :current="pageBuilder.pageNum"
            :size="page.size"
            :total="page.total"
            :page-size="page.pageSize"
            :page-size-opts="page.pageSizeOpts"
            :show-sizer="page.showSizer"
            :simple="page.simple"
            :show-elevator="page.showElevator"
            :show-total="page.showTotal"
            @on-change="onPageNumChange"
            @on-page-size-change="onPageSizeChange"/>
    </div>
    <div class="modal-container">
      <Modal v-model="modal.disable.show" :closable="modal.disable.closable" :mask-closable="modal.disable.maskClosable" width="360" class-name="vertical-center-modal">
        <p slot="header" style="color: #FF5722; text-align: center;">
          <font-awesome-icon icon="info-circle"/>
          禁用确认
        </p>
        <div style="text-align: center;">
          <p>
            <span>确认禁用【</span>
            <span v-for="(item, index) in table.selectedRows" :key="index">
              <span>{{ item.userName }} {{ item.name }}</span>
              <span v-if="index !== table.selectedRows.length - 1">、</span>
            </span>
            <span>】吗？</span>
          </p>
        </div>
        <div slot="footer">
          <Button type="error" size="large" long :loading="modal.disable.loading" @click="confirmDisable">禁用</Button>
        </div>
      </Modal>
      <Modal v-model="modal.enable.show" :closable="modal.enable.closable" :mask-closable="modal.enable.maskClosable" width="360" class-name="vertical-center-modal">
        <p slot="header" style="color: #4CAF50; text-align: center;">
          <font-awesome-icon icon="info-circle"/>
          启用确认
        </p>
        <div style="text-align: center;">
          <p>
            <span>确认启用【</span>
            <span v-for="(item, index) in table.selectedRows" :key="index">
              <span>{{ item.userName }} {{ item.name }}</span>
              <span v-if="index !== table.selectedRows.length - 1">、</span>
            </span>
            <span>】吗？</span>
          </p>
        </div>
        <div slot="footer">
          <Button type="success" size="large" long :loading="modal.enable.loading" @click="confirmEnable">启用</Button>
        </div>
      </Modal>
      <Modal width='650'
            v-model="modal.save.show"
            :fullscreen="modal.save.isFullScreen"
            :closable="modal.save.closable"
            :mask-closable="false"
            footer-hide @on-ok="modal.save.show = false"
            @on-cancel="closeSaveModal"
            class-name="vertical-center-modal">
        <p slot="header" class="text-center">{{ modal.save.title }}</p>
        <div>
          <user-save
            v-if="modal.save.show"
            :userId="modal.save.userId"
            :userCode="modal.save.userCode"
            :isModified="modal.save.isModified"
            :isModifiedRoles="modal.save.isModifiedRoles"
            :oriTeacherName="modal.save.teacherName"
            v-on:failFillFrom="failFillFrom"
            v-on:saveSuccess="saveSuccess"
            v-on:triggerClosable="modal.save.closable = $event"
          ></user-save>
        </div>
      </Modal>
    </div>
  </div>
</template>

<script>
import { mapActions } from 'vuex'
import UserSave from '_c/user-save/user-save'
import { getInstituteList, getUserList, updateUserStatus } from '@/api/user-mgmt'
import { activeTableMove } from '@/libs/tools'
import { library } from '@fortawesome/fontawesome-svg-core'
import { faEdit, faPlusCircle, faBan, faDotCircle, faMinusCircle, faCheckCircle, faInfoCircle } from '@fortawesome/free-solid-svg-icons'
library.add(faEdit)
library.add(faBan)
library.add(faDotCircle)
library.add(faPlusCircle)
library.add(faMinusCircle)
library.add(faCheckCircle)
library.add(faInfoCircle)
export default {
  name: 'UserList',
  components: {
    'user-save': UserSave
  },
  data () {
    return {
      firstEnter: false,
      title: '用户列表',
      btnSize: 'small',
      selectSize: 'default',
      enabledPreventOverflow: false,
      timer: '',
      search: {
        criteria: '',
        keyword: ''
      },
      filter: {
        departments: '',
        name: '',
        code: '',
        tel: '',
        email: '',
        identity: 'all',
        enabled: 'all',
        roles: 'all'
      },
      userAccess: [],
      institute: '',
      roleOptions: [{
        label: '系统管理员',
        value: 'ROLE_ROOT'
      }, {
        label: '校级管理员',
        value: 'ROLE_SCHOOL_ADMIN'
      }, {
        label: '学院管理员',
        value: 'ROLE_INSTITUTE_ADMIN'
      }, {
        label: '教师',
        value: 'ROLE_TEACHER'
      }, {
        label: '学生助理',
        value: 'ROLE_STUDENT_ASSISTANT'
      }, {
        label: '学生',
        value: 'ROLE_STUDENT'
      }, {
        label: '普通用户',
        value: 'ROLE_USER'
      }],
      options: {
        institutes: []
      },
      table: {
        showBorder: true,
        showStripe: false,
        showHeader: true,
        fixedHeader: true,
        height: '',
        sortableColumns: [],
        disabledHover: false,
        highlightRow: false,
        loading: false,
        size: 'small',
        selection: [],
        currRowIndex: '',
        columns: [{
          type: 'selection',
          width: 40,
          align: 'center'
        }, {
          type: 'index',
          title: '序号',
          width: 50,
          align: 'center'
        }, {
          title: '学院',
          key: 'department',
          minWidth: 120,
          align: 'center'
          // filters: undefined,
          // filterRemote: function (value) {
          //   this.filter.departments = value.length <= 0 ? [] : value
          //   if (this.filter.departments.length > 0) {
          //     this.getTableColumnByKey('department')[0].filteredValue = this.filter.departments
          //   } else {
          //     delete this.getTableColumnByKey('department')[0].filteredValue
          //   }
          // },
          // filterMultiple: true
        }, {
          title: '名称',
          key: 'name',
          minWidth: 70,
          align: 'center'
        }, {
          title: '工号',
          key: 'userName',
          minWidth: 100,
          align: 'center'
        }, {
          title: '身份',
          width: 70,
          key: 'identity',
          align: 'center',
          // filters: [{
          //   label: '教职工',
          //   value: 'Teacher'
          // }, {
          //   label: '学生',
          //   value: 'Student'
          // }],
          // filterMultiple: false,
          // filterRemote: function (value) {
          //   this.filter.identity = value.length <= 0 ? '' : value[0]
          //   // 动态设置筛选列的filteredValue，防止iview表格点击列排序时把filters清空（显示上）
          //   if (this.filter.identity) {
          //     this.getTableColumnByKey('identity')[0].filteredValue = [this.filter.identity]
          //   } else {
          //     delete this.getTableColumnByKey('identity')[0].filteredValue
          //   }
          // },
          render: (h, params) => {
            const row = params.row
            const identity = {
              'Teacher': '教师',
              'Student': '学生',
              'Other': '临时',
              'Phone': '访客',
              'Adult': '继续教育学院学生',
              'Staff': '职工'
            }
            const text = identity[row.identity] || '无'
            return h('span', text)
          }
        }, {
          title: '手机号',
          key: 'tel',
          minWidth: 90,
          align: 'center',
          render: (h, params) => {
            return h('span', params.row.tel ? params.row.tel : '无')
          }
        }, {
          title: '邮箱',
          key: 'email',
          minWidth: 145,
          align: 'center',
          render: (h, params) => {
            return h('span', params.row.email ? params.row.email : '无')
          }
        }, {
          title: '状态',
          width: 90,
          key: 'status',
          align: 'center',
          // filters: [{
          //   label: '正常',
          //   value: true
          // }, {
          //   label: '禁用',
          //   value: false
          // }],
          // filterMultiple: false,
          // filterRemote: function (value) {
          //   this.filter.enabled = value.length <= 0 ? '' : value[0]
          //   // 动态设置筛选列的filteredValue，防止iview表格点击列排序时把filters清空（显示上）
          //   if (this.filter.enabled !== '') {
          //     this.getTableColumnByKey('status')[0].filteredValue = [this.filter.enabled]
          //   } else {
          //     delete this.getTableColumnByKey('status')[0].filteredValue
          //   }
          // },
          render: (h, params) => {
            const row = params.row
            const color = row.enabled ? 'success' : 'warning'
            const text = row.enabled ? '正常' : '禁用'
            return h('Tag', {
              props: {
                color: color,
                type: 'dot'
              }
            }, text)
          }
        }, {
          title: '权限',
          width: 95,
          key: 'role',
          align: 'center',
          // filters: [{
          //   label: '系统管理员',
          //   value: 'ROLE_ROOT'
          // }, {
          //   label: '校级管理员',
          //   value: 'ROLE_SCHOOL_ADMIN'
          // }, {
          //   label: '学院管理员',
          //   value: 'ROLE_INSTITUTE_ADMIN'
          // }, {
          //   label: '教师',
          //   value: 'ROLE_TEACHER'
          // }, {
          //   label: '学生助理',
          //   value: 'ROLE_STUDENT_ASSISTANT'
          // }, {
          //   label: '学生',
          //   value: 'ROLE_STUDENT'
          // }, {
          //   label: '普通用户',
          //   value: 'ROLE_USER'
          // }],
          // filterMultiple: true,
          // filterRemote: function (value) {
          //   this.filter.roles = value.length <= 0 ? [] : value
          //   if (this.filter.roles.length > 0) {
          //     this.getTableColumnByKey('role')[0].filteredValue = this.filter.roles
          //   } else {
          //     delete this.getTableColumnByKey('role')[0].filteredValue
          //   }
          // },
          render: (h, params) => {
            const badge = {
              'ROLE_ROOT': ['dot-root', '系统管理员'],
              'ROLE_SCHOOL_ADMIN': ['dot-school-admin', '校级管理员'],
              'ROLE_INSTITUTE_ADMIN': ['dot-institute-admin', '学院管理员'],
              'ROLE_TEACHER': ['dot-teacher', '教师'],
              'ROLE_STUDENT_ASSISTANT': ['dot-assistant', '学生助理'],
              'ROLE_STUDENT': ['dot-student', '学生'],
              'ROLE_USER': ['dot-user', '普通用户']
            }
            return h('div', {
              style: {
                textAlign: 'left',
                marginTop: '5px',
                marginBottom: '5px',
                marginLeft: '5px'
              }
            },
            params.row.roles.map((item, index) => {
              return h('div', [
                h('Badge', {
                  props: {
                    text: badge[item.name] ? badge[item.name][1] : item.name,
                    status: 'default'
                  },
                  'class': badge[item.name] ? badge[item.name][0] : ''
                }),
                h('br', {
                  style: {
                    display: (index === params.row.roles.length - 1) ? 'none' : ''
                  }
                })
              ])
            }))
          }
        }, {
          title: '创建时间',
          key: 'signUpTime',
          width: 80,
          align: 'center',
          sortType: 'normal',
          sortable: 'custom',
          sortMethod: (a, b, type) => {
          }
        }, {
          title: '最后登录',
          key: 'lastSignInTime',
          width: 80,
          align: 'center',
          sortType: 'normal',
          sortable: 'custom',
          sortMethod: (a, b, type) => {
          }
        }, {
          title: '操作',
          slot: 'action',
          width: 80,
          align: 'center',
          fixed: 'right'
        }],
        data: [],
        selectedRows: []
      },
      page: {
        size: 'small',
        total: 0,
        pageSize: 10,
        showSizer: true,
        showElevator: true,
        showTotal: true,
        pageSizeOpts: [5, 10, 20, 30, 40, 50],
        simple: false
      },
      pageBuilder: {
        pageSize: 10,
        pageNum: 1,
        order: []
      },
      pageBuilderOrder: new Map(),
      /*
       * vue的响应式系统不支持Map和Set,
       * 当Map与Set里面的元素变化时，
       * Vue追踪不到这些变化，无法做出响应
       * 解决方法是用一个可序列化的变量来手动追踪变化
       */
      pageBuilderOrderChangeTracker: 1,
      modal: {
        save: {
          show: false,
          title: '新增用户',
          isFullScreen: false,
          userId: null,
          userCode: null,
          isModified: true,
          isModifiedRoles: true,
          closable: true
        },
        disable: {
          loading: false,
          show: false,
          closable: true,
          maskClosable: true
        },
        enable: {
          loading: false,
          show: false,
          closable: true,
          maskClosable: true
        }
      }
    }
  },
  computed: {
    // 搜索输入框的placeholder
    inputPlaceholder () {
      let placeholder = ''
      switch (this.search.criteria) {
        case 'name':
          placeholder = '请输入姓名进行搜索...'
          break
        case 'code':
          placeholder = '请输入工号进行搜索...'
          break
        case 'tel':
          placeholder = '请输入手机号进行搜索...'
          break
        case 'email':
          placeholder = '请输入邮箱进行搜索...'
          break
        default:
          placeholder = '请先选择搜索条件'
          break
      }
      return placeholder
    }
  },
  methods: {
    ...mapActions([
      'getUserInfo'
    ]),
    async renderTable (filter, pageBuilder) {
      if (this.timer) clearTimeout(this.timer)
      this.timer = setTimeout(async () => {
        // 初始化表格
        this.table.loading = true
        try {
          let response = await getUserList(filter, pageBuilder)
          let res = response.data
          if (res.code === 1) {
            res.data.content.forEach(item => {
              item._disabled = this.isDisabled(item.roles)
            })
            this.table.data = res.data.content
            this.page.total = res.data.totalElements
            this.$nextTick(() => {
              this.table.loading = false
            })
          } else {
            this.table.loading = false
            this.table.data = []
            this.$Notice.error({
              title: '列表加载失败',
              desc: '用户列表加载失败！' + res.info + '请重试！'
            })
          }
        } catch (error) {
          this.table.loading = false
          this.table.data = []
          this.$Notice.error({
            title: '列表加载失败',
            desc: '用户列表加载失败！请重试！'
          })
          console.log(error)
        }
      }, 300)
    },
    // 添加用户
    addUser () {
      this.modal.save = Object.assign(this.modal.save, {
        show: true,
        title: '新增用户',
        userId: null,
        userCode: null,
        isModified: false,
        isModifiedRoles: false,
        closable: true
      })
    },
    // 修改用户信息
    edit (row) {
      this.modal.save = Object.assign(this.modal.save, {
        show: true,
        title: '用户【' + row.userName + row.name + '】的权限',
        userId: row.id,
        userCode: row.userName,
        isModified: true,
        isModifiedRoles: true,
        closable: true
      })
    },
    // 修改用户填充表单失败
    failFillFrom (info) {
      this.modal.save.show = false
      this.$nextTick(() => {
        // 全局配置notice组件的属性
        this.$Notice.config({
          top: window.innerHeight / 3
        })
        this.$nextTick(() => {
          this.$Notice.error({
            title: '获取用户信息失败，请稍后重试',
            desc: info
          })
        })
      })
    },
    // 成功 新增 / 修改 用户
    saveSuccess (isModified) {
      this.modal.save.show = false
      this.$nextTick(() => {
        // 全局配置notice组件的属性
        this.$Notice.config({
          top: window.innerHeight / 3
        })
        this.$nextTick(() => {
          this.$Notice.success({
            title: '提交成功',
            desc: isModified ? '修改用户信息成功' : '新增用户成功'
          })
        })
      })
      if (isModified) {
        // 从当前状态重新加载表格
        this.renderTable(this.filter, this.pageBuilder)
      } else {
        this.$emit('refresh')
      }
    },
    // 启用用户
    enable (row) {
      this.modal.enable.show = true
      this.table.selectedRows = [row]
    },
    // 批量启用用户
    batchEnable () {
      if (this.table.selection.length <= 0) {
        this.$Notice.warning({
          title: '提示',
          desc: '请先选择需要批量启用的用户！'
        })
      } else {
        this.table.selectedRows = this.table.selection
        this.modal.enable.show = true
      }
    },
    // 确认启用
    confirmEnable () {
      this.modal.enable.loading = true
      this.modal.enable.closable = false
      this.modal.enable.maskClosable = false
      updateUserStatus(this.table.selectedRows.map(item => {
        return item.id
      }), true).then(response => {
        let res = response.data
        this.modal.enable.loading = false
        this.modal.enable.show = false
        this.modal.enable.closable = true
        this.modal.enable.maskClosable = true
        if (res.code === 1) {
          this.$Notice.success({
            title: '启用成功',
            desc: '启用所选用户成功！'
          })
          // 从当前状态重新加载表格
          this.renderTable(this.filter, this.pageBuilder)
        } else {
          this.$Notice.error({
            title: '启用失败',
            desc: '启用所选用户失败！' + res.info + '请重试！'
          })
        }
      }).catch(err => {
        console.log(err)
        this.modal.enable.loading = false
        this.modal.enable.show = false
        this.modal.enable.closable = true
        this.modal.enable.maskClosable = true
        this.$Notice.error({
          title: '启用失败',
          desc: '启用所选用户失败！请重试！'
        })
      })
    },
    // 禁用用户
    disable (row) {
      this.modal.disable.show = true
      this.table.selectedRows = [row]
    },
    // 批量禁用用户
    batchDisable () {
      if (this.table.selection.length <= 0) {
        this.$Notice.warning({
          title: '提示',
          desc: '请先选择需要批量禁用的用户！'
        })
      } else {
        this.table.selectedRows = this.table.selection
        this.modal.disable.show = true
      }
    },
    // 确认禁用
    confirmDisable () {
      this.modal.disable.loading = true
      this.modal.disable.closable = false
      this.modal.disable.maskClosable = false
      updateUserStatus(this.table.selectedRows.map(item => {
        return item.id
      }), false).then(response => {
        let res = response.data
        this.modal.disable.loading = false
        this.modal.disable.show = false
        this.modal.disable.closable = true
        this.modal.disable.maskClosable = true
        if (res.code === 1) {
          this.$Notice.success({
            title: '禁用成功',
            desc: '禁用所选用户成功！'
          })
          // 从当前状态重新加载表格
          this.renderTable(this.filter, this.pageBuilder)
        } else {
          this.$Notice.error({
            title: '禁用失败',
            desc: '禁用所选用户失败！' + res.info + '请重试！'
          })
        }
      }).catch(err => {
        console.log(err)
        this.modal.disable.loading = false
        this.modal.disable.show = false
        this.modal.disable.closable = true
        this.modal.disable.maskClosable = true
        this.$Notice.error({
          title: '禁用失败',
          desc: '禁用所选用户失败！请重试！'
        })
      })
    },
    // 选择搜索条件后触发
    onChangeSearchCriteria (value) {
      this.search.keyword = ''
      this.filter.name = ''
      this.filter.code = ''
      this.filter.tel = ''
      this.filter.email = ''
      this.search.criteria = value
    },
    // 输入框点击搜索或按下回车键时触发
    onSearch (value) {
      this.filter.name = ''
      this.filter.code = ''
      this.filter.tel = ''
      this.filter.email = ''
      if (this.search.keyword.replace(/(^\s*)|(\s*$)/g, '').length <= 0) {
        // this.$Message.warning({
        //   content: '搜索的关键字不能为空！',
        //   closable: true
        // })
        this.$Notice.warning({
          title: '提示',
          desc: '搜索的关键字不能为空！'
        })
      } else {
        this.search.keyword = this.search.keyword.replace(/(^\s*)|(\s*$)/g, '')
        this.filter[this.search.criteria] = this.search.keyword
      }
    },
    // 输入框数据改变时触发
    onInputChange (value) {
      this.filter.name = ''
      this.filter.code = ''
      this.filter.tel = ''
      this.filter.email = ''
      if (this.search.keyword.replace(/(^\s*)|(\s*$)/g, '').length <= 0) {
        this.$Notice.warning({
          title: '提示',
          desc: '搜索的关键字不能为空！'
        })
      } else {
        this.search.keyword = this.search.keyword.replace(/(^\s*)|(\s*$)/g, '')
        this.filter[this.search.criteria] = this.search.keyword
      }
    },
    // 排序时有效，当点击排序时触发
    onSortChange (column) {
      this.pageBuilderOrder.set(column.key, column.order)
      this.pageBuilderOrderChangeTracker++
    },
    // 在多选模式下有效，只要选中项发生变化时就会触发
    onSelectionChange (selection) {
      this.table.selection = selection
    },
    // 页码改变的回调，返回改变后的页码
    onPageNumChange (value) {
      this.pageBuilder.pageNum = value
    },
    // 切换每页条数时的回调，返回切换后的每页条数
    onPageSizeChange (value) {
      this.pageBuilder.pageNum = 1
      this.pageBuilder.pageSize = value
    },
    getSortableColumns (columns) {
      let sortableColumns = []
      columns.forEach(item => {
        if (item.sortable) {
          sortableColumns.push(item)
        }
        if (item.children && item.children.length > 0) {
          sortableColumns = sortableColumns.concat(this.getSortableColumns(item.children))
        }
      })
      return sortableColumns
    },
    // 关闭 新增 / 修改 用户的Modal的回调函数
    closeSaveModal () {
      this.modal.save.isModified = true
      this.$nextTick(() => {
        // 全局配置notice组件的属性
        this.$Notice.config({
          top: window.innerHeight / 3
        })
      })
    },
    isDisabled (roles) {
      roles = roles.map(item => {
        return item.name
      })
      /**
       * 1. this.userAccess.every(item => { return ['ROLE_ROOT', 'ROLE_SCHOOL_ADMIN', 'ROLE_INSTITUTE_ADMIN'].indexOf(item) < 0 }) 非 系统 / 校级 / 院级管理员，都禁用
       * 2. this.userAccess.indexOf('ROLE_ROOT') > -1 && roles.indexOf('ROLE_ROOT') > -1  是 系统管理员 且对方也为系统管理员，禁用
       * 3. this.userAccess.indexOf('ROLE_SCHOOL_ADMIN') > -1 && !this.userAccess.some(item => { return ['ROLE_ROOT'].indexOf(item) > -1 }) && roles.some(item => { return ['ROLE_ROOT', 'ROLE_SCHOOL_ADMIN'].indexOf(item) > -1 })
       * 3. 是 校级管理员，且不为 系统管理员， 对方若有 系统 / 校级管理员 权限，则禁用
       * 4. this.userAccess.indexOf('ROLE_INSTITUTE_ADMIN') > -1 && !this.userAccess.some(item => { return ['ROLE_ROOT', 'ROLE_SCHOOL_ADMIN'].indexOf(item) > -1 }) && roles.some(item => { return ['ROLE_ROOT', 'ROLE_SCHOOL_ADMIN', 'ROLE_INSTITUTE_ADMIN'].indexOf(item) > -1 })
       * 4. 是 院级管理员，且不为 系统 / 校级管理员， 对方若有 系统 / 校级 / 院级管理员 权限，则禁用
       */
      if (
        (this.userAccess.every(item => { return ['ROLE_ROOT', 'ROLE_SCHOOL_ADMIN', 'ROLE_INSTITUTE_ADMIN'].indexOf(item) < 0 })) ||
        (this.userAccess.indexOf('ROLE_ROOT') > -1 && roles.indexOf('ROLE_ROOT') > -1) ||
        (this.userAccess.indexOf('ROLE_SCHOOL_ADMIN') > -1 && !this.userAccess.some(item => { return ['ROLE_ROOT'].indexOf(item) > -1 }) && roles.some(item => { return ['ROLE_ROOT', 'ROLE_SCHOOL_ADMIN'].indexOf(item) > -1 })) ||
        (this.userAccess.indexOf('ROLE_INSTITUTE_ADMIN') > -1 && !this.userAccess.some(item => { return ['ROLE_ROOT', 'ROLE_SCHOOL_ADMIN'].indexOf(item) > -1 }) && roles.some(item => { return ['ROLE_ROOT', 'ROLE_SCHOOL_ADMIN', 'ROLE_INSTITUTE_ADMIN'].indexOf(item) > -1 }))
      ) {
        return true
      }
      return false
    },
    // 动态获取所有的表格列
    getTableColumns (columns) {
      let tableColumns = []
      columns.forEach(item => {
        if (!item.children) {
          tableColumns.push(item)
        }
        if (item.children && item.children.length > 0) {
          tableColumns = tableColumns.concat(this.getTableColumns(item.children))
        }
      })
      return tableColumns
    },
    // 根据key动态获取表格列
    getTableColumnByKey (key) {
      return this.getTableColumns(this.table.columns).filter(item => {
        return item.key === key
      })
    }
  },
  created () {
    this.firstEnter = true
    // 全局配置notice组件的属性
    this.$Notice.config({
      top: window.innerHeight / 3
    })
    // 获取权限类别
    // getRolesType().then(response => {
    //   let res = response.data
    //   // *动态设置表格列（权限类别）的filters筛选条件
    //   this.table.columns.slice(-2, -1)[0].filters = res.code === 1 && res.data ? Object.keys(res.data).map(key => {
    //     return {
    //       label: res.data[key],
    //       value: key
    //     }
    //   }) : undefined
    // }).catch(err => {
    //   this.table.columns.slice(-2, -1)[0].filters = undefined
    //   console.log(err)
    // })
    this.getUserInfo().then(response => {
      let res = response.data
      if (res.code === 1) {
        res = res.data
        this.userAccess = res.roles || []
        this.institute = res.department || ''
        this.filter.departments = this.institute || ''
        if ((this.userAccess.indexOf('ROLE_SCHOOL_ADMIN') > -1 || this.userAccess.indexOf('ROLE_ROOT') > -1) && res.department) {
          // // 获取所有学院
          // getInstituteList().then(response => {
          //   let res = response.data
          //   if (res.code === 1) {
          //     // *动态设置表格列（学院）的filters筛选条件
          //     if (res.data && res.data.length > 0) {
          //       this.table.columns.slice(2, 3)[0].filters = res.data.map(item => {
          //         return {
          //           label: item,
          //           value: item
          //         }
          //       })
          //       this.table.columns.slice(2, 3)[0].filteredValue = this.filter.departments
          //     } else {
          //       this.table.columns.slice(2, 3)[0].filters = undefined
          //     }
          //   } else {
          //     this.table.columns.slice(2, 3)[0].filters = undefined
          //     this.$Notice.error({
          //       title: '获取列表失败',
          //       desc: '获取学院列表失败！' + res.info + '请重试！'
          //     })
          //   }
          // }).catch(err => {
          //   this.table.columns.slice(2, 3)[0].filters = undefined
          //   this.$Notice.error({
          //     title: '获取列表失败',
          //     desc: '获取学院列表失败！请重试！'
          //   })
          //   console.log(err)
          // })
          // 获取所有学院
          getInstituteList().then(response => {
            let res = response.data
            if (res.code === 1) {
              this.options.institutes = res.data.length > 0 ? res.data : []
            } else {
              this.$Notice.error({
                title: '获取列表失败',
                desc: '获取学院列表失败！' + res.info
              })
            }
          }).catch(err => {
            this.$Notice.error({
              title: '获取列表失败',
              desc: '获取学院列表失败！'
            })
            console.log(err)
          })
        }
      } else {
        this.$Notice.error({
          title: '获取信息失败',
          desc: '获取用户信息失败！' + res.info + '请重试！'
        })
      }
    }).catch(err => {
      this.$Notice.error({
        title: '获取信息失败',
        desc: '获取用户信息失败！请重试！'
      })
      console.log(err)
    })
  },
  mounted () {
    this.$nextTick(() => {
      activeTableMove(document.querySelector('#user-list .ivu-table-body'))
    })
  },
  activated () {
    if (!this.firstEnter) {
      // 全局配置notice组件的属性
      this.$Notice.config({
        top: window.innerHeight / 3
      })
    }
  },
  deactivated () {
    this.firstEnter = false
    this.$Notice.destroy()
  },
  beforeDestroy () {
    this.$Notice.destroy()
  },
  watch: {
    filter: {
      handler: function (value) {
        this.pageBuilder.pageNum === 1 ? this.renderTable(value, this.pageBuilder) : this.pageBuilder.pageNum = 1
      },
      deep: true
    },
    pageBuilder: {
      handler: function (value) {
        this.renderTable(this.filter, value)
      },
      deep: true
    },
    'pageBuilder.order': function (value) {
      // iview table 默认只支持单列排序，
      // 除了调用接口进行远程排序外，
      // 还要动态设置表格列的sortType，
      // 实现样式上的显示
      if (!this.table.sortableColumns || this.table.sortableColumns.length <= 0) {
        this.table.sortableColumns = this.getSortableColumns(this.table.columns)
      }
      value.forEach(v => {
        let column = this.table.sortableColumns.filter(item => {
          return item.key === Object.keys(v)[0]
        })
        if (column && column.length > 0) {
          column[0].sortType = v[column[0].key]
        }
      })
    },
    pageBuilderOrderChangeTracker () {
      let tempArray = []
      this.pageBuilderOrder.forEach((value, key, map) => {
        if (value) {
          let obj = {}
          obj[key] = value
          tempArray = tempArray.concat([obj])
        }
      })
      this.pageBuilder.order = tempArray
    }
  }
}
</script>

<style lang="less">
  .vertical-center-modal {
    display: flex;
    align-items: center;
    justify-content: center;

    .ivu-modal{
      top: 0;
    }
  }

  .ivu-badge-status {
    &.dot {
      &-root {
        .ivu-badge-status-dot {
          background-color: rgb(126, 152, 207);
        }
      }
      &-school-admin {
        .ivu-badge-status-dot {
          background-color: #CE93D8;
        }
      }
      &-institute-admin {
        .ivu-badge-status-dot {
          background-color: #81D4FA;
        }
      }
      &-teacher {
        .ivu-badge-status-dot {
          background-color: #8fdc36;
        }
      }
      &-assistant {
        .ivu-badge-status-dot {
          background-color: #FFF176;
        }
      }
      &-student {
        .ivu-badge-status-dot {
          background-color: #f16286;
        }
      }
      &-user {
        .ivu-badge-status-dot {
          background-color: #FFAB91;
        }
      }
    }
  }
</style>
